package com.x.dictionary.service;

import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Objects;
import java.util.ServiceLoader;

/**
 * 字典服务类-管理字典服务实现类
 *
 * @author xulihua
 * @date 2021/9/8 17:27
 */
@Slf4j
public class DictionaryService {

    /**
     * 服务类
     */
    private static DictionaryService service;
    /**
     * 加载器
     */
    private final ServiceLoader<Dictionary> loader;

    /**
     * 构造时加载字典服务的实现类
     */
    public DictionaryService() {
        loader = ServiceLoader.load(Dictionary.class);
    }

    /**
     * 创建单例的service
     *
     * @return DictionaryService
     */
    public static synchronized DictionaryService getService() {
        if (Objects.isNull(service)) {
            service = new DictionaryService();
        }
        return service;
    }

    /**
     * 服务实现方法
     *
     * @param word：传入的词汇
     * @return :String
     */
    public String getDefinition(String word) {
        String result = null;
        // 获取ServiceLoader中的缓存服务信息
        Iterator<Dictionary> dictionaries = loader.iterator();
        while (result == null && dictionaries.hasNext()) {
            // 获取服务类实例
            Dictionary d = dictionaries.next();
            log.info(d.name() + "进行检索");
            // 调用服务类的实现方法
            result = d.getDefinition(word);
            log.info("检索结果:" + result);
        }
        return result;
    }
}
